import Application from "../../application/application";
import { localConnectionConfig } from "../../config/connection_config";
import { SocketMessageType } from "../../enum/socket_message_enum";
import { AppSocket } from "../socket/socket";

/**
 * 连接
 */
class Connection {
  private _localConnectInstance: RTCPeerConnection | null = null;
  private _socketInstance: AppSocket | null = null;
  private _currentLocalStream: MediaStream | null = null;
  

  constructor () {
    this._init()
  }

  private _init () {
    this._localConnectInstance = new RTCPeerConnection(localConnectionConfig)
    this._socketInstance = new AppSocket()
  }

  /**
   * 添加 track
   * @param tracks 单个/多个 tracks
   * @param stream 流信息
   */
  addTrack(tracks: MediaStreamTrack | MediaStreamTrack[], stream: MediaStream) : void {
    this._currentLocalStream = stream;

    if (tracks instanceof Array) {
      tracks.forEach(track => {
        this._localConnectInstance?.addTrack(track, stream)
      })

      return
    }
    this._localConnectInstance?.addTrack(tracks, stream)

    this._publish()
  }

  /**
   * 发布当前流信息
   */
  private async _publish () {
    const offer = await this._localConnectInstance?.createOffer()
    this._localConnectInstance?.setLocalDescription(offer)

    
    this._socketInstance?.send(SocketMessageType.offer, {
      type: SocketMessageType.offer,
      data: {
        roomName: Application.roomName,
        userId: Application.localUserInfo?.userId,
        offer: offer
      }
    })
  }

  /**
   * 
   */
  stopTranscribe () {
    this._stopStreamPublish()
  }

  _stopStreamPublish () {}

}

export default Connection